package com.qilu.pe.ui.activity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.dao.bean.Product;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.GlideUtil;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class ProDetailActivity extends Base2Activity {
    private ViewPager vp;
    private TextView tv_price, tv_desc, tv_info;// 价格,描述,详情
    private TextView tv_buy;// 购买
    private WebView webview;

    private VpAdapter adapter;

    private String id;// 传过来的商品id
    private Product product;// 请求得到的商品详情

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_pro_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vp = findViewById(R.id.vp);
        tv_price = findViewById(R.id.tv_price);
        tv_desc = findViewById(R.id.tv_desc);
        tv_info = findViewById(R.id.tv_info);
        webview = findViewById(R.id.webview);
        tv_buy = findViewById(R.id.tv_buy);

        setHeadTitle("产品详情");

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            id = bundle.getString("id");
        }

        adapter = new VpAdapter();
        vp.setAdapter(adapter);

        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();

        setListeners();

        showProgress();
        reqProDetail();
    }

    private void setListeners() {
        setOnClickListener(tv_buy);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_buy) {
            if (null == product) {
                ToastUtils.showShort("数据加载中,请稍候");
                return;
            }
            showDialog();
        }
    }

    private Disposable reqProDetail() {
        return APIRetrofit.getDefault().reqProductDetail(id)
                .compose(RxUtil.<BaseResult2<Product>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<Product>>() {
                    @Override
                    public void accept(BaseResult2<Product> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {

                        } else {

                        }
                        product = result2.getData();
                        setProductData();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private void setProductData() {
        if (null != product) {
            adapter.notifyDataSetChanged();
            tv_price.setText("¥" + product.getPrice());
            tv_desc.setText(product.getName());
//            tv_info.setText(product.getInfo());
            initWebview(product.getInfo());
        }
    }

    private void initWebview(String url) {
        // 开启js支持
        webview.getSettings().setJavaScriptEnabled(true);
        //2、关闭自动适应
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(false);
        // 3、//重写WebViewClient中的onPageFinished方法
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //修改图片大小
                int screenWidth = ScreenUtils.getScreenWidth();
//                String width = String.valueOf(screenWidth - SizeUtils.dp2px(50));
//                String width2 = String.valueOf(screenWidth - SizeUtils.dp2px(10));
                String width2 = String.valueOf(SizeUtils.px2dp(screenWidth) - 15);

                String javascript = "javascript:function ResizeImages() {" +
                        "var myimg,oldwidth;" +
                        "var maxwidth = document.body.clientWidth;" +
                        "for(i=0;i <document.images.length;i++){" +
                        "myimg = document.images[i];" +
//                        "myimg.margin = 0;" +
                        "if(myimg.width > " + width2 + "){" +
                        "oldwidth = myimg.width;" +
                        "myimg.width =" + width2 + ";" +
                        "}" +
                        "}" +
                        "}";
                view.loadUrl(javascript);
                view.loadUrl("javascript:ResizeImages();");
            }
        });
        webview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
//        webview.loadUrl(url);
        webview.loadData(url, "text/html;charset=utf-8", null); // 加载定义的代码，并设定编码格式和字符集。
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;
    private int num = 1;// 记录输入的商品数量

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(this, R.layout.layout_alert_buy_product, null);

        final TextView tv_num = alert_view.findViewById(R.id.tv_num);
        final TextView tv_minus = alert_view.findViewById(R.id.tv_minus);
        final TextView tv_plus = alert_view.findViewById(R.id.tv_plus);
        RoundedImageView iv_product = alert_view.findViewById(R.id.iv_product);
        GlideUtil.loadImg(Config.URL_IMG + product.getPicture(), iv_product);

        tv_num.setText("" + num);

        tv_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = Integer.parseInt(tv_num.getText().toString().trim());
                num -= 1;
                if (num <= 1) {
                    num = 1;
                }
                tv_num.setText("" + num);
            }
        });
        tv_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = Integer.parseInt(tv_num.getText().toString().trim());
                num += 1;
                tv_num.setText("" + num);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
                Bundle bundle = new Bundle();
                bundle.putSerializable("product", product);
                bundle.putString("num", num + "");
                startActivity(GenProductOrderActivity.class, bundle);
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, this);
    }

    private class VpAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView iv = new ImageView(ProDetailActivity.this);
            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);

//            iv.setImageResource(R.drawable.home_top_banner);
            if (null != product) {
                GlideUtil.loadImg(Config.URL_IMG + product.getPicture(), iv);
            }

            container.addView(iv);
            return iv;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((ImageView) object);
        }
    }
}